/*
 * Copyright © 2010 SenseForce.com.
 * The Software shall be used for Good, not Evil.
 */

package com.senseforce.classes;

import javax.microedition.lcdui.*;
import com.senseforce.midlets.ShortMessage;

/**
 *
 * @author jcccn
 * @site http://www.senseforce.com/
 */
public class MessageEditForm extends Form implements CommandListener, ItemStateListener {
	
	private ShortMessage midlet;
	private Command backCommand = new Command("Back", Command.BACK, 0);
	private Command deleteCommand = new Command("Delete", Command.CANCEL, 0);
	private Command sendCommand = new Command("Send", Command.SCREEN, 0);
		
	private TextField msgContentTextField = new TextField(null, null, 140, TextField.ANY);
	
	public MessageEditForm(String title, ShortMessage midlet) {
		super(title);
		this.midlet = midlet;
		
		setItemStateListener(this);
		msgContentTextField.setLayout(Item.LAYOUT_VEXPAND);
                append(msgContentTextField);
		msgContentTextField.setPreferredSize(getWidth(), getHeight());
		
		setCommandListener(this);
		addCommand(backCommand);
		addCommand(sendCommand);
	}

        public void clearContent() {
            msgContentTextField.setString(null);
			removeCommand(deleteCommand);
			addCommand(backCommand);
        }
	
	public void commandAction(Command c, Displayable d) {
		if (c == backCommand) {
			midlet.changeFormWithType(MessageConfig.FORMTYPE_WELCOME);
		}
		else if (c == deleteCommand) {
			int caretPosition = msgContentTextField.getCaretPosition();
			if (caretPosition > 0) {
				msgContentTextField.delete(caretPosition-1, 1);
				if (msgContentTextField.size() == 0) {
					removeCommand(deleteCommand);
					addCommand(backCommand);
				}
			}
		}
		else if (c == sendCommand) {
			MessageConfig.MESSAGE = msgContentTextField.getString();
			midlet.changeFormWithType(MessageConfig.FORMTYPE_SEND);
		}
	}
	
	public void itemStateChanged(Item item){
		if (item == msgContentTextField) {
			if (msgContentTextField.size() != 0) {
				removeCommand(backCommand);
				addCommand(deleteCommand);
			}
		}
	}
}
